package com.sj.mbt.ui.nearby;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.sj.friendcircle.common.router.RouterList;
import com.sj.mbt.R;
import com.sj.mbt.ui.adapter.PoepleNearbyAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.rongcloud.im.SealAppContext;
import cn.rongcloud.im.server.broadcast.BroadcastManager;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.response.BaseResponse;
import cn.rongcloud.im.server.response.PeopleNearbyResponse;
import cn.rongcloud.im.server.utils.NToast;
import cn.rongcloud.im.server.widget.LoadDialog;
import cn.rongcloud.im.ui.activity.base.BaseActivity;
import cn.rongcloud.im.utils.ShareUtil;

/**
 * 附近的人
 */
@Route(path = RouterList.PeopleNearbyActivity.path)
public class PeopleNearbyActivity extends BaseActivity implements AMapLocationListener, OnRefreshListener, OnLoadMoreListener {

    private static final int USER_LOCATION_OPEN = 1;
    private static final int USER_LOCATION_LIST_BY_PAGE = 2;
    private static final int USER_LOCATION_CLOSE = 3;

    @BindView(R.id.recycler_view)
    LRecyclerView recyclerView;

    private double latitude;
    private double longitude;
    private int pageNum = 1;
    private PoepleNearbyAdapter adapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_people_nearby);
        ButterKnife.bind(this);

        setTitle("附近的人");
        Button rightButton = getHeadRightButton();
        rightButton.setBackground(getResources().getDrawable(R.mipmap.abc_top_bar_right_clear));
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request(USER_LOCATION_CLOSE);
            }
        });
        LoadDialog.show(mContext);
        initView();
        initMap();
    }

    private void initView() {
        adapter = new PoepleNearbyAdapter(mContext);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        recyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        recyclerView.setOnRefreshListener(this);
        recyclerView.setOnLoadMoreListener(this);
    }

    private void initMap() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //设置是否单次定位
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                latitude = aMapLocation.getLatitude();
                longitude = aMapLocation.getLongitude();
                aMapLocation.getAccuracy();//获取精度信息
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date = new Date(aMapLocation.getTime());
//                df.format(date);//定位时间
                request(USER_LOCATION_OPEN);
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }

    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        switch (requestCode) {
            case USER_LOCATION_OPEN:
                return action.userLocationOpen(latitude + "", longitude + "");
            case USER_LOCATION_LIST_BY_PAGE:
                return action.userLocationListByPage(pageNum, 20);
            case USER_LOCATION_CLOSE:
                return action.userLocationClose();
        }
        return super.doInBackground(requestCode, id);
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        if (result != null) {
            switch (requestCode) {
                case USER_LOCATION_OPEN:
                    BaseResponse baseResponse = (BaseResponse) result;
                    if (baseResponse.getResultCode() == 0) {
                        ShareUtil.putData(mContext,"isPeopleNearby",true);
                        BroadcastManager.getInstance(mContext).sendBroadcast(SealAppContext.UPDATE_FOOTPRINT);

                        request(USER_LOCATION_LIST_BY_PAGE);
                    } else {
                        NToast.shortToast(mContext, baseResponse.getMsg());
                    }
                    break;
                case USER_LOCATION_LIST_BY_PAGE:
                    PeopleNearbyResponse scrres = (PeopleNearbyResponse) result;
                    if (scrres.getResultCode() == 0) {
                        List<PeopleNearbyResponse.DataBean> data = scrres.getData();
                        if (data == null && data.size() == 0){
                            recyclerView.setNoMore(true);
                            return;
                        }
                        PoepleNearbyAdapter innerAdapter = (PoepleNearbyAdapter) lRecyclerViewAdapter.getInnerAdapter();
                        if (pageNum == 1){
                            recyclerView.setNoMore(false);
                            innerAdapter.setDataList(data);
                        }else {
                            innerAdapter.addAll(data);
                        }
                        recyclerView.refreshComplete(scrres.getData().size());
                        lRecyclerViewAdapter.notifyDataSetChanged();
//                        LocalJsonUtil.getInstance().setPhoneContact(mContext, data);
//                        for (MachineFragment fragment : adapter.getmFragments()) {
//                            fragment.setData(data);
//                        }
                    } else {
                        NToast.shortToast(mContext, scrres.getMsg());
                    }
                    LoadDialog.dismiss(mContext);
                    break;
                case USER_LOCATION_CLOSE:
                    BaseResponse baseResponse1 = (BaseResponse) result;
                    if (baseResponse1.getResultCode() == 0) {
                        ShareUtil.putData(mContext,"isPeopleNearby",false);
                        BroadcastManager.getInstance(mContext).sendBroadcast(SealAppContext.UPDATE_FOOTPRINT);
                        finish();
                        NToast.shortToast(mContext, baseResponse1.getMsg());
                    } else {
                        NToast.shortToast(mContext, baseResponse1.getMsg());
                    }
                    LoadDialog.dismiss(mContext);
                    break;
            }
        }
    }

    @Override
    public void onFailure(int requestCode, int state, Object result) {
        switch (requestCode) {
            default:
                LoadDialog.dismiss(mContext);
                NToast.shortToast(mContext, "请求失败！");
                break;
        }
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        request(USER_LOCATION_LIST_BY_PAGE);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        request(USER_LOCATION_LIST_BY_PAGE);
    }
}
